import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jst认证成功返回数据
    :param token:
    :param user:
    :param request:
    :return:
    """

    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'mobile': user.mobile,
        'avatar': user.avatar
    }


def get_user_by_account(account):
    """ 添加手机号查询用户的方法"""
    try:
        if re.match(r'^1[356789]\d{9}$', account):
            user = User.objects.get(mobile=account)
        else:
            user = User.objects.get(username=account)
    except User.DoesNotExist:
        return None


    return user


# 重写认证方法

class UserByUsernameModile(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):

        if request is None:
            try:
                user = User.objects.get(username=username)
            except:
                return None


            if user.check_password(password):
                return user


        else:
            user = get_user_by_account(username)

            if user.check_password(password=password):

                return user
